package mspbots.cw.callbacks.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import mspbots.cw.common.RabbitKeys;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * com.mspbots.sync.config.RabbitConfigurer
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/29
 */
@Configuration
public class RabbitConfiguration {

    private final AmqpAdmin amqpAdmin;
    private final Exchange exchange;

    Map<String, Object> args = new HashMap<>(2) {{
        put("x-dead-letter-exchange", RabbitKeys.BASE_EXCHANGE_NAME);
        put("x-dead-letter-routing-key", RabbitKeys.BAD_MESSAGE_QUEUE_KEY);
    }};

    public RabbitConfiguration(AmqpAdmin amqpAdmin) {
        this.amqpAdmin = amqpAdmin;
        this.exchange = ExchangeBuilder.directExchange(RabbitKeys.BASE_EXCHANGE_NAME).build();
        this.amqpAdmin.declareExchange(exchange);
    }

    @Bean
    public void declareBaseExchange() {
        Queue queue = QueueBuilder.durable("connect-wise.bad.message")
                .withArgument("x-message-ttl", 1000 * 60 * 60 * 24).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange)
                .with(RabbitKeys.BAD_MESSAGE_QUEUE_KEY).noargs());

        queue = QueueBuilder.durable("connect-wise.logs.task.sync").withArguments(args).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange)
                .with(RabbitKeys.LOGS_TASK_QUEUE_KEY).noargs());

    }


    @Bean
    public MessageConverter rabbitMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
